package org.ldx.lotterysystem.common.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.ldx.lotterysystem.common.utils.JWTUtil;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 请求之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取请求头
        String token = request.getHeader("user_token");
        log.info("获取token{}",token);
        log.info("获取路径{}",request.getRequestURL());
        //解析令牌
        Claims claims = JWTUtil.parseJWT(token);
        if(null == claims){
            log.error("解析JWT失败!");
            response.setStatus(401);
            return false;
        }
        log.info("JWT解析成功");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
